Google Vs. Apple Correlation Arbitrage Trading Algorithms | By Andrew Conti

This notebook contains an algorithm designed to profit off of the correlation between Apple's and Google's common stock in December 2012 to May 2012. It explores the process of developing the algorithm from conception to full maturation. The final algorithm returns 14.1% in only 128 trading days after commission fees and accounting for slippage.

This notebook and the data used in this example is located at http://github.com/agconti/AGCTrading.


In [12]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

from scipy.stats import pearsonr
from zipline.algorithm import TradingAlgorithm
from zipline.transforms import MovingAverage, batch_transform
from zipline.utils.factory import load_from_yahoo
from zipline.finance import slippage, commission

In [13]:
# Uncomment the line below to get the data for yourself, but it is already included in the above mentioned repository
#data = load_from_yahoo(stocks=['AAPL', 'GOOG'],start=datetime.datetime(2012,11,1), end=datetime.datetime(2013,5,8)); data.save('goog_aapl_tests.dat')
data = pd.load('goog_aapl_tests.dat')

Here is the phenomenon:

Throughout 2012 Apple's and Google's stocks were moving relatively together with respect to primary trends. After January 2013, the stocks diverge in a highly correlated but generally negative fashion.


In [14]:
fig = plt.figure(figsize(12,6))

#data.SPX.plot(label='S&P Benchmark')
data.GOOG.plot()
data.AAPL.plot()

legend(loc='best')
plt.title("Apple & Google Adj Closing Prices")


Out[14]:
<matplotlib.text.Text at 0x4e38d6a0>

The Trading Algorithm:

Here is the most basic version of our algorithm and will be refined later in the notebook. It works by comparing the prices between Google and Apple,( self.pricea for Apple and self.priceg for Google), and then buys or sells the stock if the correlation, corr, of the stocks in the last 5 days is greater than our set minimun correlation value, self.corr_tolerance. To determine whether to buy or sell Google, it checks the movement of Apple's stock. If Apple went down yesterday relative to today, it buys Google; if apple's stock went up it sells Google.

Here's a look for the coded logic for buying and selling Google:

    if self.priceg < self.priceglag and np.abs(corr) > self.corr_tolerance:
        self.order('AAPL',-100)
        self.sell_orders.append((data.AAPL.datetime, pval))
        print "{dt}: Selling 100 AAPL shares.".format(dt = data.AAPL.datetime)
    elif self.priceg > self.priceglag and np.abs(corr) > self.corr_tolerance:
        self.order('AAPL',100)
        self.buy_orders.append((data.AAPL.datetime, pval))
        print "{dt}: Buying 100 AAPL shares.".format(dt = data.AAPL.datetime)


The algorithm use the same logic to trade Apple's stock. In this way, the pricing algorithm makes sure that the two stocks have indeed been following each other and then trades each stock by the other's divergence. The full algorithm is shown below:


In [15]:
class GOOG_AAPL_COR(TradingAlgorithm): # inherit from TradingAlgorithm
    """
    Google Apple Correlation algorithm.

    An algorithm designed to exploit the correlation in the movement of Apple's and 
    Google's common stock. 
    """
    def initialize(self):
        self.capital_base = 1000000
        self.pricea = 0
        self.priceg = 0
        self.window_length = 5 
        self.corr_tolerance = 0.9
        self.max_notional = self.capital_base + 0.1
        self.min_notional = self.capital_base * (-1) 
        self.pricealag = 0
        self.priceglag = 0
        self.buy_orders = []
        self.sell_orders = [] 
        self.corr_values_aapl = []
        self.corr_values_goog = []

    def handle_data(self, data):

        self.pricea = data.AAPL.price
        self.priceg = data.GOOG.price   
        
        # compute correlation between stocks
        corr, pval = self.correlation(data, self.pricea, self.priceg)
        print str(data.AAPL.datetime) + ': Pearson Correlation: ' + str(corr) # print results to console

        #notional = self.portfolio.positions[data.AAPL].amount * pricea
        #notional = notional + self.portfolio.positions[data.GOOG].amount * priceg 
        

        # Decision logic
        if self.priceg < self.priceglag and np.abs(corr) > self.corr_tolerance:
            self.order('AAPL',-100)
            self.sell_orders.append((data.AAPL.datetime, pval)) # save the order pval and time for analysis later on
            print "{dt}: Selling 100 AAPL shares.".format(dt = data.AAPL.datetime)  
        elif self.priceg > self.priceglag and np.abs(corr) > self.corr_tolerance:
            self.order('AAPL',100)
            self.buy_orders.append((data.AAPL.datetime, pval))
            print "{dt}: Buying 100 AAPL shares.".format(dt = data.AAPL.datetime)

        if self.pricea < self.pricealag and  np.abs(corr) > self.corr_tolerance:
            self.order('GOOG',-100)
            self.sell_orders.append((data.GOOG.datetime, pval))
            print "{dt}: Selling 100 GOOG shares.".format(dt = data.GOOG.datetime)
        elif self.pricea > self.pricealag and np.abs(corr) > self.corr_tolerance:
            self.order('GOOG',100)
            self.buy_orders.append((data.GOOG.datetime, pval))  
            print "{dt}: Buying 100 GOOG shares.".format(dt = data.GOOG.datetime)

        # lag price variables 
        self.pricealag = data.AAPL.price
        self.priceglag = data.GOOG.price
    
    # correlation method
    def correlation(self, data, pricea, priceg):
        self.corr_values_aapl.append(pricea)
        self.corr_values_goog.append(priceg)
        corr = pearsonr(self.corr_values_aapl[-self.window_length:], self.corr_values_goog[-self.window_length:])
        return corr

Lets simulate our algorithm on historical daily returns, from November 2012 through May 2013:


In [16]:
GOOG_AAPL_COR = GOOG_AAPL_COR()
results_GOOG_AAPL_COR = GOOG_AAPL_COR.run(data)


2012-11-01 00:00:00+00:00: Pearson Correlation: nan
2012-11-02 00:00:00+00:00: Pearson Correlation: -1.0
2012-11-02 00:00:00+00:00: Buying 100 AAPL shares.
2012-11-02 00:00:00+00:00: Selling 100 GOOG shares.
2012-11-05 00:00:00+00:00: Pearson Correlation: 0.059824040231
2012-11-06 00:00:00+00:00: Pearson Correlation: 0.174659180436
2012-11-07 00:00:00+00:00: Pearson Correlation: 0.824233785309
2012-11-08 00:00:00+00:00: Pearson Correlation: 0.952297709192
2012-11-08 00:00:00+00:00: Selling 100 AAPL shares.
2012-11-08 00:00:00+00:00: Selling 100 GOOG shares.
2012-11-09 00:00:00+00:00: Pearson Correlation: 0.991554650251
2012-11-09 00:00:00+00:00: Buying 100 AAPL shares.
2012-11-09 00:00:00+00:00: Buying 100 GOOG shares.
2012-11-12 00:00:00+00:00: Pearson Correlation: 0.929368022202
2012-11-12 00:00:00+00:00: Buying 100 AAPL shares.
2012-11-12 00:00:00+00:00: Selling 100 GOOG shares.
2012-11-13 00:00:00+00:00: Pearson Correlation: 0.757576476824
2012-11-14 00:00:00+00:00: Pearson Correlation: 0.845836369332
2012-11-15 00:00:00+00:00: Pearson Correlation: 0.904363385855
2012-11-15 00:00:00+00:00: Selling 100 AAPL shares.
2012-11-15 00:00:00+00:00: Selling 100 GOOG shares.
2012-11-16 00:00:00+00:00: Pearson Correlation: 0.919167495476
2012-11-16 00:00:00+00:00: Selling 100 AAPL shares.
2012-11-16 00:00:00+00:00: Buying 100 GOOG shares.
2012-11-19 00:00:00+00:00: Pearson Correlation: 0.98644535697
2012-11-19 00:00:00+00:00: Buying 100 AAPL shares.
2012-11-19 00:00:00+00:00: Buying 100 GOOG shares.
2012-11-20 00:00:00+00:00: Pearson Correlation: 0.988017374005
2012-11-20 00:00:00+00:00: Buying 100 AAPL shares.
2012-11-20 00:00:00+00:00: Selling 100 GOOG shares.
2012-11-21 00:00:00+00:00: Pearson Correlation: 0.98614541901
2012-11-21 00:00:00+00:00: Selling 100 AAPL shares.
2012-11-21 00:00:00+00:00: Buying 100 GOOG shares.
2012-11-23 00:00:00+00:00: Pearson Correlation: 0.956502301266
2012-11-23 00:00:00+00:00: Buying 100 AAPL shares.
2012-11-23 00:00:00+00:00: Buying 100 GOOG shares.
2012-11-26 00:00:00+00:00: Pearson Correlation: -0.850795924042
2012-11-27 00:00:00+00:00: Pearson Correlation: -0.388234458157
2012-11-28 00:00:00+00:00: Pearson Correlation: 0.132856328942
2012-11-29 00:00:00+00:00: Pearson Correlation: 0.244364901771
2012-11-30 00:00:00+00:00: Pearson Correlation: -0.233575324747
2012-12-03 00:00:00+00:00: Pearson Correlation: 0.394085687777
2012-12-04 00:00:00+00:00: Pearson Correlation: 0.281478815016
2012-12-05 00:00:00+00:00: Pearson Correlation: 0.738307236796
2012-12-06 00:00:00+00:00: Pearson Correlation: 0.840028399437
2012-12-07 00:00:00+00:00: Pearson Correlation: 0.87515944915
2012-12-10 00:00:00+00:00: Pearson Correlation: 0.793381038641
2012-12-11 00:00:00+00:00: Pearson Correlation: 0.699662917774
2012-12-12 00:00:00+00:00: Pearson Correlation: 0.61994502866
2012-12-13 00:00:00+00:00: Pearson Correlation: 0.269620004501
2012-12-14 00:00:00+00:00: Pearson Correlation: -0.279590717582
2012-12-17 00:00:00+00:00: Pearson Correlation: -0.546140037064
2012-12-18 00:00:00+00:00: Pearson Correlation: -0.0881216339673
2012-12-19 00:00:00+00:00: Pearson Correlation: 0.403905418053
2012-12-20 00:00:00+00:00: Pearson Correlation: 0.755250505131
2012-12-21 00:00:00+00:00: Pearson Correlation: 0.339476408109
2012-12-24 00:00:00+00:00: Pearson Correlation: 0.549057229948
2012-12-26 00:00:00+00:00: Pearson Correlation: 0.739033938857
2012-12-27 00:00:00+00:00: Pearson Correlation: 0.744796824599
2012-12-28 00:00:00+00:00: Pearson Correlation: 0.821945371289
2012-12-31 00:00:00+00:00: Pearson Correlation: 0.466884246454
2013-01-02 00:00:00+00:00: Pearson Correlation: 0.876920310513
2013-01-03 00:00:00+00:00: Pearson Correlation: 0.927515534537
2013-01-03 00:00:00+00:00: Buying 100 AAPL shares.
2013-01-03 00:00:00+00:00: Selling 100 GOOG shares.
2013-01-04 00:00:00+00:00: Pearson Correlation: 0.494477226709
2013-01-07 00:00:00+00:00: Pearson Correlation: -0.387391976151
2013-01-08 00:00:00+00:00: Pearson Correlation: -0.927721502534
2013-01-08 00:00:00+00:00: Selling 100 AAPL shares.
2013-01-08 00:00:00+00:00: Buying 100 GOOG shares.
2013-01-09 00:00:00+00:00: Pearson Correlation: -0.909803583801
2013-01-09 00:00:00+00:00: Buying 100 AAPL shares.
2013-01-09 00:00:00+00:00: Selling 100 GOOG shares.
2013-01-10 00:00:00+00:00: Pearson Correlation: -0.233228339811
2013-01-11 00:00:00+00:00: Pearson Correlation: -0.446151532632
2013-01-14 00:00:00+00:00: Pearson Correlation: 0.806202475541
2013-01-15 00:00:00+00:00: Pearson Correlation: 0.907783047386
2013-01-15 00:00:00+00:00: Buying 100 AAPL shares.
2013-01-15 00:00:00+00:00: Selling 100 GOOG shares.
2013-01-16 00:00:00+00:00: Pearson Correlation: 0.696926220586
2013-01-17 00:00:00+00:00: Pearson Correlation: 0.442689440196
2013-01-18 00:00:00+00:00: Pearson Correlation: -0.496565907528
2013-01-22 00:00:00+00:00: Pearson Correlation: -0.717758128217
2013-01-23 00:00:00+00:00: Pearson Correlation: 0.91836915185
2013-01-23 00:00:00+00:00: Buying 100 AAPL shares.
2013-01-23 00:00:00+00:00: Buying 100 GOOG shares.
2013-01-24 00:00:00+00:00: Pearson Correlation: -0.601692961309
2013-01-25 00:00:00+00:00: Pearson Correlation: -0.703340810332
2013-01-28 00:00:00+00:00: Pearson Correlation: -0.708631151794
2013-01-29 00:00:00+00:00: Pearson Correlation: -0.942863822082
2013-01-29 00:00:00+00:00: Buying 100 AAPL shares.
2013-01-29 00:00:00+00:00: Buying 100 GOOG shares.
2013-01-30 00:00:00+00:00: Pearson Correlation: 0.105071788809
2013-01-31 00:00:00+00:00: Pearson Correlation: 0.267677939369
2013-02-01 00:00:00+00:00: Pearson Correlation: -0.0734603761372
2013-02-04 00:00:00+00:00: Pearson Correlation: -0.199311330537
2013-02-05 00:00:00+00:00: Pearson Correlation: 0.0510478602377
2013-02-06 00:00:00+00:00: Pearson Correlation: 0.353566175356
2013-02-07 00:00:00+00:00: Pearson Correlation: 0.693378247595
2013-02-08 00:00:00+00:00: Pearson Correlation: 0.952514956078
2013-02-08 00:00:00+00:00: Buying 100 AAPL shares.
2013-02-08 00:00:00+00:00: Buying 100 GOOG shares.
2013-02-11 00:00:00+00:00: Pearson Correlation: 0.922284099348
2013-02-11 00:00:00+00:00: Selling 100 AAPL shares.
2013-02-11 00:00:00+00:00: Buying 100 GOOG shares.
2013-02-12 00:00:00+00:00: Pearson Correlation: 0.855718558992
2013-02-13 00:00:00+00:00: Pearson Correlation: 0.442512222602
2013-02-14 00:00:00+00:00: Pearson Correlation: -0.15909805662
2013-02-15 00:00:00+00:00: Pearson Correlation: -0.660823444996
2013-02-19 00:00:00+00:00: Pearson Correlation: -0.873349113446
2013-02-20 00:00:00+00:00: Pearson Correlation: -0.373572157847
2013-02-21 00:00:00+00:00: Pearson Correlation: -0.101445899412
2013-02-22 00:00:00+00:00: Pearson Correlation: 0.398375188553
2013-02-25 00:00:00+00:00: Pearson Correlation: 0.935757136186
2013-02-25 00:00:00+00:00: Selling 100 AAPL shares.
2013-02-25 00:00:00+00:00: Selling 100 GOOG shares.
2013-02-26 00:00:00+00:00: Pearson Correlation: 0.488289511759
2013-02-27 00:00:00+00:00: Pearson Correlation: 0.236926672758
2013-02-28 00:00:00+00:00: Pearson Correlation: -0.134727207432
2013-03-01 00:00:00+00:00: Pearson Correlation: -0.800766068617
2013-03-04 00:00:00+00:00: Pearson Correlation: -0.966418239347
2013-03-04 00:00:00+00:00: Buying 100 AAPL shares.
2013-03-04 00:00:00+00:00: Selling 100 GOOG shares.
2013-03-05 00:00:00+00:00: Pearson Correlation: -0.612146269391
2013-03-06 00:00:00+00:00: Pearson Correlation: -0.523858670059
2013-03-07 00:00:00+00:00: Pearson Correlation: 0.128313159843
2013-03-08 00:00:00+00:00: Pearson Correlation: 0.856768169064
2013-03-11 00:00:00+00:00: Pearson Correlation: 0.37064308425
2013-03-12 00:00:00+00:00: Pearson Correlation: 0.694439233109
2013-03-13 00:00:00+00:00: Pearson Correlation: 0.848864875018
2013-03-14 00:00:00+00:00: Pearson Correlation: 0.583850851016
2013-03-15 00:00:00+00:00: Pearson Correlation: -0.382247521161
2013-03-18 00:00:00+00:00: Pearson Correlation: -0.986326278298
2013-03-18 00:00:00+00:00: Selling 100 AAPL shares.
2013-03-18 00:00:00+00:00: Buying 100 GOOG shares.
2013-03-19 00:00:00+00:00: Pearson Correlation: -0.982469497378
2013-03-19 00:00:00+00:00: Buying 100 AAPL shares.
2013-03-19 00:00:00+00:00: Selling 100 GOOG shares.
2013-03-20 00:00:00+00:00: Pearson Correlation: -0.916359799195
2013-03-20 00:00:00+00:00: Buying 100 AAPL shares.
2013-03-20 00:00:00+00:00: Selling 100 GOOG shares.
2013-03-21 00:00:00+00:00: Pearson Correlation: -0.69849547277
2013-03-22 00:00:00+00:00: Pearson Correlation: -0.483088392126
2013-03-25 00:00:00+00:00: Pearson Correlation: -0.769950032764
2013-03-26 00:00:00+00:00: Pearson Correlation: -0.692494102481
2013-03-27 00:00:00+00:00: Pearson Correlation: 0.534907310429
2013-03-28 00:00:00+00:00: Pearson Correlation: 0.973183362731
2013-03-28 00:00:00+00:00: Selling 100 AAPL shares.
2013-03-28 00:00:00+00:00: Selling 100 GOOG shares.
2013-04-01 00:00:00+00:00: Pearson Correlation: 0.726670249705
2013-04-02 00:00:00+00:00: Pearson Correlation: 0.143611794748
2013-04-03 00:00:00+00:00: Pearson Correlation: -0.465442720063
2013-04-04 00:00:00+00:00: Pearson Correlation: -0.395440571443
2013-04-05 00:00:00+00:00: Pearson Correlation: 0.888941897899
2013-04-08 00:00:00+00:00: Pearson Correlation: 0.799236827344
2013-04-09 00:00:00+00:00: Pearson Correlation: 0.759685868182
2013-04-10 00:00:00+00:00: Pearson Correlation: 0.457328874099
2013-04-11 00:00:00+00:00: Pearson Correlation: 0.780718813282
2013-04-12 00:00:00+00:00: Pearson Correlation: 0.863304390263
2013-04-15 00:00:00+00:00: Pearson Correlation: 0.724997330538
2013-04-16 00:00:00+00:00: Pearson Correlation: 0.623692113603
2013-04-17 00:00:00+00:00: Pearson Correlation: 0.744004178512
2013-04-18 00:00:00+00:00: Pearson Correlation: 0.894304567757
[2013-06-04 16:48] INFO: Performance: Simulated 128 trading days out of 128.
[2013-06-04 16:48] INFO: Performance: first open: 2012-11-01 13:30:00+00:00
[2013-06-04 16:48] INFO: Performance: last close: 2013-05-07 20:00:00+00:00
2013-04-19 00:00:00+00:00: Pearson Correlation: 0.204682970752
2013-04-22 00:00:00+00:00: Pearson Correlation: 0.203268615806
2013-04-23 00:00:00+00:00: Pearson Correlation: 0.408273152978
2013-04-24 00:00:00+00:00: Pearson Correlation: 0.696724629857
2013-04-25 00:00:00+00:00: Pearson Correlation: 0.829059086718
2013-04-26 00:00:00+00:00: Pearson Correlation: -0.0460241057536
2013-04-29 00:00:00+00:00: Pearson Correlation: 0.405794075795
2013-04-30 00:00:00+00:00: Pearson Correlation: 0.707738144101
2013-05-01 00:00:00+00:00: Pearson Correlation: 0.859529936421
2013-05-02 00:00:00+00:00: Pearson Correlation: 0.964752298038
2013-05-02 00:00:00+00:00: Buying 100 AAPL shares.
2013-05-02 00:00:00+00:00: Buying 100 GOOG shares.
2013-05-03 00:00:00+00:00: Pearson Correlation: 0.838557400323
2013-05-06 00:00:00+00:00: Pearson Correlation: 0.985339456603
2013-05-06 00:00:00+00:00: Buying 100 AAPL shares.
2013-05-06 00:00:00+00:00: Buying 100 GOOG shares.
2013-05-07 00:00:00+00:00: Pearson Correlation: 0.987890482366
2013-05-07 00:00:00+00:00: Selling 100 AAPL shares.
2013-05-07 00:00:00+00:00: Selling 100 GOOG shares.

Below is a graphical analysis of its performance:

The first chart is a plot of movement of Apple and Google's stock price during our simulation period. The second plots the date at which we bought and sold stock by the relative confidence of that trade. Our confidence is expressed as a p-value of the Pearson correlation coefficient. The lower the p-value, the more confident we are that the correlation is not random chance. The next two plots track our portfolio value and the returns of the portfolio throughout our simulation.


In [17]:
plt.figure(figsize(18,10), dpi=1600)

# plot 1 
ax1 = plt.subplot(411)
data[['GOOG', 'AAPL']].plot(ax=ax1)
plt.ylabel('Price')
plt.setp(ax1.get_xticklabels(), visible=False) # hide plot 1 x axis labels
plt.title("GOOG_AAPL_COR Results")

# prepare data for plot 2
GOOG_AAPL_COR.buy_orders = np.asarray(GOOG_AAPL_COR.buy_orders)
GOOG_AAPL_COR.sell_orders = np.asarray(GOOG_AAPL_COR.sell_orders)

#plot 2
ax2 = plt.subplot(412, sharex=ax1)
plt.plot(GOOG_AAPL_COR.buy_orders[:,0], GOOG_AAPL_COR.buy_orders[:,1], color = 'g')
plt.plot(GOOG_AAPL_COR.sell_orders[:,0], GOOG_AAPL_COR.sell_orders[:,1], color = 'r')
plt.plot(GOOG_AAPL_COR.buy_orders[:,0], GOOG_AAPL_COR.buy_orders[:,1], '^', c='g', markersize=10, label='buy')
plt.plot(GOOG_AAPL_COR.sell_orders[:,0], GOOG_AAPL_COR.sell_orders[:,1], 'v', c='r', markersize=10, label='sell')
plt.ylabel('P-Value')
plt.grid(color = 'k')
plt.setp(ax2.get_xticklabels(), visible=False)
plt.legend()

# plot 3
ax3 = plt.subplot(413, sharex=ax1)
results_GOOG_AAPL_COR.portfolio_value.plot()
plt.ylabel('Portfolio Value')
plt.setp(ax3.get_xticklabels(), visible=False)
plt.legend()

#plot 4
ax4 = plt.subplot(414, sharex=ax1)
results_GOOG_AAPL_COR.portfolio_value.pct_change().plot()
plt.ylabel('Portfolio % Change')
plt.legend(loc='best')


Out[17]:
<matplotlib.legend.Legend at 0x4dbc22b0>

In [18]:
results_GOOG_AAPL_COR.portfolio_value.describe() # show the summary statistics for our portfolio value


Out[18]:
count        128.000000
mean      967163.396008
std        21977.717181
min       921489.828000
25%       947888.435500
50%       961277.381000
75%       986565.932000
max      1000000.000000
dtype: float64

In [19]:
results_GOOG_AAPL_COR.portfolio_value.pct_change().apply(lambda x: x * 100).describe() # show the summary statistics for our returns


Out[19]:
count    127.000000
mean      -0.037103
std        0.467640
min       -2.852347
25%       -0.175055
50%       -0.036696
75%        0.230159
max        0.979195
dtype: float64

In [20]:
# Plot the distribution of the returns
fig = plt.figure(figsize(8,4))
results_GOOG_AAPL_COR.portfolio_value.pct_change().dropna().plot(kind='kde')
plt.xlabel=('Returns')
title("The Distribution of the Returns for\nGOOG_AAPL_COR")


Out[20]:
<matplotlib.text.Text at 0x4e37f0f0>

The Results:

As you can see, the performance of the algorithm is poor. On average, it bled 0.03% per day. On its best day it gained just under a percent, (0.98%), and on its worst it lost 2.852%. Throughout its trading our algorithm experienced a protracted drawdown and finished below its high-water mark at $952,641.669, a 4.735% loss. The upside? There is tons of potential.

Lets do better.

Lets clean the signal from the noise by adjusting Apple and Google's returns by the S&P returns. Through this process we are reducing the systematic noise in the movements of the two stock prices and getting closer to the actual signals of the two firm's movements. Below is a graphic representation of the process:


In [21]:
fig = plt.figure(figsize(18, 10), dpi=1600)

ax1 = fig.add_subplot(211)
data.SPX.plot(label='S&P Benchmark')
data.GOOG.plot()
data.AAPL.plot()
plt.ylabel(r'Stock / Index Value')
legend(loc='best')
plt.setp(ax1.get_xticklabels(), visible=False)
plt.title("Adj Closing Prices")

ax2 = fig.add_subplot(212, sharex=ax1)
(data.SPX.pct_change() - data.SPX.pct_change()).plot(label='S&P Benchmark, flatlined')
(data.GOOG.pct_change() - data.SPX.pct_change()).plot(label='GOOG adj for var in S&P')
(data.AAPL.pct_change() - data.SPX.pct_change()).plot(label='AAPL adj for var in S&P')
plt.ylabel("Daily Return")
legend(loc='best')
plt.title("Adj Closing Prices adjusted for S&P movements")


Out[21]:
<matplotlib.text.Text at 0x4d690358>

Let's incorporate this idea into our algorithm:

From now on we will use the day's percent change, or the day's return, instead of the adjusted closing price of the stock. Before we decide whether to buy or sell, we adjust the return by the return of the S&P in the same period. Then we will trade the stock if they are within our correlation tolerance. If the return is positive for the opposing partner we buy the stock; if the return is negative we sell the stock.

The resulting trading algorithm is shown below:


In [22]:
class GOOG_AAPL_COR_V_SP500(TradingAlgorithm): # inherit from TradingAlgorithm
  """
  Google Apple Correlation algorithm adjusted for movements in the S&P500.

  An algorithm designed to exploit the correlation in the movement of Apple's and 
  Google's common stock. 
  """
  def initialize(self):
    self.capital_base = 1000000
    self.pricea = 0
    self.priceg = 0
    self.pricespx = 0
    self.window_length = 5 
    self.corr_tolerance = 0.9
    self.max_notional = self.capital_base + 0.1
    self.min_notional = self.capital_base * (-1) 
    self.pricealag = 0
    self.priceglag = 0
    self.pricespxlag = 0
    self.buy_orders = []
    self.sell_orders = [] 
    self.corr_values_aapl = []
    self.corr_values_goog = []

  def handle_data(self, data):
    self.pricea = data.AAPL.price 
    self.priceg = data.GOOG.price  
    self.pricespx = data.SPX.price

    # find percent change and substract movements from SPX
    aapl_mov, goog_mov = self.spx_adjust(data, self.pricea, self.priceg, self.pricespx, self.pricealag, self.priceglag, self.pricespxlag)

    # calculate the correlation between the stocks
    corr, pval = self.correlation(data, self.pricea, self.priceg)
    print str(data.AAPL.datetime) + ': Pearson Correlation: ' + str(corr) # print results to console
    
    
    #notional = self.portfolio.positions[data.AAPL].amount * pricea
    #notional = notional + self.portfolio.positions[data.GOOG].amount * priceg 

    # Decision Logic
    if goog_mov < 0 and np.abs(corr) > self.corr_tolerance:
      self.order('AAPL',-100)
      self.sell_orders.append((data.AAPL.datetime, pval)) # save the order amount and time for analysis
      print "{dt}: Selling 100 AAPL shares.".format(dt = data.AAPL.datetime)
    elif goog_mov > 0 and np.abs(corr) > self.corr_tolerance:
      self.order('AAPL',100)
      self.buy_orders.append((data.AAPL.datetime, pval))
      print "{dt}: Buying 100 AAPL shares.".format(dt = data.AAPL.datetime)

    if aapl_mov < 0 and  np.abs(corr) > self.corr_tolerance:
      self.order('GOOG',-100)
      self.sell_orders.append((data.GOOG.datetime, pval))
      print "{dt}: Selling 100 GOOG shares.".format(dt = data.GOOG.datetime)
    elif aapl_mov > 0 and np.abs(corr) > self.corr_tolerance:
      self.order('GOOG',100)
      self.buy_orders.append((data.GOOG.datetime, pval))  
      print "{dt}: Buying 100 GOOG shares.".format(dt = data.GOOG.datetime)

    # lag price variables 
    self.pricealag = data.AAPL.price
    self.priceglag = data.GOOG.price
    self.pricespxlag =  data.SPX.price

  def correlation(self, data, pricea, priceg):
    self.corr_values_aapl.append(self.pricea)
    self.corr_values_goog.append(self.priceg)
    corr = pearsonr(self.corr_values_aapl[-self.window_length:], self.corr_values_goog[-self.window_length:]) # [0] only get the correltion
    return corr

  def per_change(self, data, begin, end):
    percent_change = ((end - begin)/begin)
    return percent_change
    
  def spx_adjust(self, data, pricea, priceg, pricespx, pricealag, priceglag, pricespxlag):
    spx_change = self.per_change(data, pricespx, self.pricespxlag)
    aapl_change = (self.per_change(data, pricea, self.pricealag) - spx_change)
    goog_change = (self.per_change(data, priceg, self.priceglag) - spx_change)
    return (aapl_change, goog_change)

In [23]:
GOOG_AAPL_COR_V_SP500 = GOOG_AAPL_COR_V_SP500()
results_GOOG_AAPL_COR_V_SP500 = GOOG_AAPL_COR_V_SP500.run(data)


2012-11-01 00:00:00+00:00: Pearson Correlation: nan
2012-11-02 00:00:00+00:00: Pearson Correlation: -1.0
2012-11-02 00:00:00+00:00: Selling 100 AAPL shares.
2012-11-02 00:00:00+00:00: Buying 100 GOOG shares.
2012-11-05 00:00:00+00:00: Pearson Correlation: 0.059824040231
2012-11-06 00:00:00+00:00: Pearson Correlation: 0.174659180436
2012-11-07 00:00:00+00:00: Pearson Correlation: 0.824233785309
2012-11-08 00:00:00+00:00: Pearson Correlation: 0.952297709192
2012-11-08 00:00:00+00:00: Buying 100 AAPL shares.
2012-11-08 00:00:00+00:00: Buying 100 GOOG shares.
2012-11-09 00:00:00+00:00: Pearson Correlation: 0.991554650251
2012-11-09 00:00:00+00:00: Selling 100 AAPL shares.
2012-11-09 00:00:00+00:00: Selling 100 GOOG shares.
2012-11-12 00:00:00+00:00: Pearson Correlation: 0.929368022202
2012-11-12 00:00:00+00:00: Selling 100 AAPL shares.
2012-11-12 00:00:00+00:00: Buying 100 GOOG shares.
2012-11-13 00:00:00+00:00: Pearson Correlation: 0.757576476824
2012-11-14 00:00:00+00:00: Pearson Correlation: 0.845836369332
2012-11-15 00:00:00+00:00: Pearson Correlation: 0.904363385855
2012-11-15 00:00:00+00:00: Buying 100 AAPL shares.
2012-11-15 00:00:00+00:00: Buying 100 GOOG shares.
2012-11-16 00:00:00+00:00: Pearson Correlation: 0.919167495476
2012-11-16 00:00:00+00:00: Buying 100 AAPL shares.
2012-11-16 00:00:00+00:00: Buying 100 GOOG shares.
2012-11-19 00:00:00+00:00: Pearson Correlation: 0.98644535697
2012-11-19 00:00:00+00:00: Selling 100 AAPL shares.
2012-11-19 00:00:00+00:00: Selling 100 GOOG shares.
2012-11-20 00:00:00+00:00: Pearson Correlation: 0.988017374005
2012-11-20 00:00:00+00:00: Selling 100 AAPL shares.
2012-11-20 00:00:00+00:00: Buying 100 GOOG shares.
2012-11-21 00:00:00+00:00: Pearson Correlation: 0.98614541901
2012-11-21 00:00:00+00:00: Buying 100 AAPL shares.
2012-11-21 00:00:00+00:00: Buying 100 GOOG shares.
2012-11-23 00:00:00+00:00: Pearson Correlation: 0.956502301266
2012-11-23 00:00:00+00:00: Buying 100 AAPL shares.
2012-11-23 00:00:00+00:00: Selling 100 GOOG shares.
2012-11-26 00:00:00+00:00: Pearson Correlation: -0.850795924042
2012-11-27 00:00:00+00:00: Pearson Correlation: -0.388234458157
2012-11-28 00:00:00+00:00: Pearson Correlation: 0.132856328942
2012-11-29 00:00:00+00:00: Pearson Correlation: 0.244364901771
2012-11-30 00:00:00+00:00: Pearson Correlation: -0.233575324747
2012-12-03 00:00:00+00:00: Pearson Correlation: 0.394085687777
2012-12-04 00:00:00+00:00: Pearson Correlation: 0.281478815016
2012-12-05 00:00:00+00:00: Pearson Correlation: 0.738307236796
2012-12-06 00:00:00+00:00: Pearson Correlation: 0.840028399437
2012-12-07 00:00:00+00:00: Pearson Correlation: 0.87515944915
2012-12-10 00:00:00+00:00: Pearson Correlation: 0.793381038641
2012-12-11 00:00:00+00:00: Pearson Correlation: 0.699662917774
2012-12-12 00:00:00+00:00: Pearson Correlation: 0.61994502866
2012-12-13 00:00:00+00:00: Pearson Correlation: 0.269620004501
2012-12-14 00:00:00+00:00: Pearson Correlation: -0.279590717582
2012-12-17 00:00:00+00:00: Pearson Correlation: -0.546140037064
2012-12-18 00:00:00+00:00: Pearson Correlation: -0.0881216339673
2012-12-19 00:00:00+00:00: Pearson Correlation: 0.403905418053
2012-12-20 00:00:00+00:00: Pearson Correlation: 0.755250505131
2012-12-21 00:00:00+00:00: Pearson Correlation: 0.339476408109
2012-12-24 00:00:00+00:00: Pearson Correlation: 0.549057229948
2012-12-26 00:00:00+00:00: Pearson Correlation: 0.739033938857
2012-12-27 00:00:00+00:00: Pearson Correlation: 0.744796824599
2012-12-28 00:00:00+00:00: Pearson Correlation: 0.821945371289
2012-12-31 00:00:00+00:00: Pearson Correlation: 0.466884246454
2013-01-02 00:00:00+00:00: Pearson Correlation: 0.876920310513
2013-01-03 00:00:00+00:00: Pearson Correlation: 0.927515534537
2013-01-03 00:00:00+00:00: Selling 100 AAPL shares.
2013-01-03 00:00:00+00:00: Buying 100 GOOG shares.
2013-01-04 00:00:00+00:00: Pearson Correlation: 0.494477226709
2013-01-07 00:00:00+00:00: Pearson Correlation: -0.387391976151
2013-01-08 00:00:00+00:00: Pearson Correlation: -0.927721502534
2013-01-08 00:00:00+00:00: Selling 100 AAPL shares.
2013-01-08 00:00:00+00:00: Selling 100 GOOG shares.
2013-01-09 00:00:00+00:00: Pearson Correlation: -0.909803583801
2013-01-09 00:00:00+00:00: Selling 100 AAPL shares.
2013-01-09 00:00:00+00:00: Buying 100 GOOG shares.
2013-01-10 00:00:00+00:00: Pearson Correlation: -0.233228339811
2013-01-11 00:00:00+00:00: Pearson Correlation: -0.446151532632
2013-01-14 00:00:00+00:00: Pearson Correlation: 0.806202475541
2013-01-15 00:00:00+00:00: Pearson Correlation: 0.907783047386
2013-01-15 00:00:00+00:00: Selling 100 AAPL shares.
2013-01-15 00:00:00+00:00: Buying 100 GOOG shares.
2013-01-16 00:00:00+00:00: Pearson Correlation: 0.696926220586
2013-01-17 00:00:00+00:00: Pearson Correlation: 0.442689440196
2013-01-18 00:00:00+00:00: Pearson Correlation: -0.496565907528
2013-01-22 00:00:00+00:00: Pearson Correlation: -0.717758128217
2013-01-23 00:00:00+00:00: Pearson Correlation: 0.91836915185
2013-01-23 00:00:00+00:00: Selling 100 AAPL shares.
2013-01-23 00:00:00+00:00: Selling 100 GOOG shares.
2013-01-24 00:00:00+00:00: Pearson Correlation: -0.601692961309
2013-01-25 00:00:00+00:00: Pearson Correlation: -0.703340810332
2013-01-28 00:00:00+00:00: Pearson Correlation: -0.708631151794
2013-01-29 00:00:00+00:00: Pearson Correlation: -0.942863822082
2013-01-29 00:00:00+00:00: Buying 100 AAPL shares.
2013-01-29 00:00:00+00:00: Selling 100 GOOG shares.
2013-01-30 00:00:00+00:00: Pearson Correlation: 0.105071788809
2013-01-31 00:00:00+00:00: Pearson Correlation: 0.267677939369
2013-02-01 00:00:00+00:00: Pearson Correlation: -0.0734603761372
2013-02-04 00:00:00+00:00: Pearson Correlation: -0.199311330537
2013-02-05 00:00:00+00:00: Pearson Correlation: 0.0510478602377
2013-02-06 00:00:00+00:00: Pearson Correlation: 0.353566175356
2013-02-07 00:00:00+00:00: Pearson Correlation: 0.693378247595
2013-02-08 00:00:00+00:00: Pearson Correlation: 0.952514956078
2013-02-08 00:00:00+00:00: Selling 100 AAPL shares.
2013-02-08 00:00:00+00:00: Selling 100 GOOG shares.
2013-02-11 00:00:00+00:00: Pearson Correlation: 0.922284099348
2013-02-11 00:00:00+00:00: Buying 100 AAPL shares.
2013-02-11 00:00:00+00:00: Selling 100 GOOG shares.
2013-02-12 00:00:00+00:00: Pearson Correlation: 0.855718558992
2013-02-13 00:00:00+00:00: Pearson Correlation: 0.442512222602
2013-02-14 00:00:00+00:00: Pearson Correlation: -0.15909805662
2013-02-15 00:00:00+00:00: Pearson Correlation: -0.660823444996
2013-02-19 00:00:00+00:00: Pearson Correlation: -0.873349113446
2013-02-20 00:00:00+00:00: Pearson Correlation: -0.373572157847
2013-02-21 00:00:00+00:00: Pearson Correlation: -0.101445899412
2013-02-22 00:00:00+00:00: Pearson Correlation: 0.398375188553
2013-02-25 00:00:00+00:00: Pearson Correlation: 0.935757136186
2013-02-25 00:00:00+00:00: Selling 100 AAPL shares.
2013-02-25 00:00:00+00:00: Selling 100 GOOG shares.
2013-02-26 00:00:00+00:00: Pearson Correlation: 0.488289511759
2013-02-27 00:00:00+00:00: Pearson Correlation: 0.236926672758
2013-02-28 00:00:00+00:00: Pearson Correlation: -0.134727207432
2013-03-01 00:00:00+00:00: Pearson Correlation: -0.800766068617
2013-03-04 00:00:00+00:00: Pearson Correlation: -0.966418239347
2013-03-04 00:00:00+00:00: Selling 100 AAPL shares.
2013-03-04 00:00:00+00:00: Buying 100 GOOG shares.
2013-03-05 00:00:00+00:00: Pearson Correlation: -0.612146269391
2013-03-06 00:00:00+00:00: Pearson Correlation: -0.523858670059
2013-03-07 00:00:00+00:00: Pearson Correlation: 0.128313159843
2013-03-08 00:00:00+00:00: Pearson Correlation: 0.856768169064
2013-03-11 00:00:00+00:00: Pearson Correlation: 0.37064308425
2013-03-12 00:00:00+00:00: Pearson Correlation: 0.694439233109
2013-03-13 00:00:00+00:00: Pearson Correlation: 0.848864875018
2013-03-14 00:00:00+00:00: Pearson Correlation: 0.583850851016
2013-03-15 00:00:00+00:00: Pearson Correlation: -0.382247521161
2013-03-18 00:00:00+00:00: Pearson Correlation: -0.986326278298
2013-03-18 00:00:00+00:00: Buying 100 AAPL shares.
2013-03-18 00:00:00+00:00: Selling 100 GOOG shares.
2013-03-19 00:00:00+00:00: Pearson Correlation: -0.982469497378
2013-03-19 00:00:00+00:00: Selling 100 AAPL shares.
2013-03-19 00:00:00+00:00: Buying 100 GOOG shares.
2013-03-20 00:00:00+00:00: Pearson Correlation: -0.916359799195
2013-03-20 00:00:00+00:00: Buying 100 AAPL shares.
2013-03-20 00:00:00+00:00: Buying 100 GOOG shares.
2013-03-21 00:00:00+00:00: Pearson Correlation: -0.69849547277
2013-03-22 00:00:00+00:00: Pearson Correlation: -0.483088392126
2013-03-25 00:00:00+00:00: Pearson Correlation: -0.769950032764
2013-03-26 00:00:00+00:00: Pearson Correlation: -0.692494102481
2013-03-27 00:00:00+00:00: Pearson Correlation: 0.534907310429
2013-03-28 00:00:00+00:00: Pearson Correlation: 0.973183362731
2013-03-28 00:00:00+00:00: Buying 100 AAPL shares.
2013-03-28 00:00:00+00:00: Buying 100 GOOG shares.
2013-04-01 00:00:00+00:00: Pearson Correlation: 0.726670249705
2013-04-02 00:00:00+00:00: Pearson Correlation: 0.143611794748
2013-04-03 00:00:00+00:00: Pearson Correlation: -0.465442720063
2013-04-04 00:00:00+00:00: Pearson Correlation: -0.395440571443
2013-04-05 00:00:00+00:00: Pearson Correlation: 0.888941897899
2013-04-08 00:00:00+00:00: Pearson Correlation: 0.799236827344
2013-04-09 00:00:00+00:00: Pearson Correlation: 0.759685868182
2013-04-10 00:00:00+00:00: Pearson Correlation: 0.457328874099
2013-04-11 00:00:00+00:00: Pearson Correlation: 0.780718813282
2013-04-12 00:00:00+00:00: Pearson Correlation: 0.863304390263
2013-04-15 00:00:00+00:00: Pearson Correlation: 0.724997330538
2013-04-16 00:00:00+00:00: Pearson Correlation: 0.623692113603
2013-04-17 00:00:00+00:00: Pearson Correlation: 0.744004178512
2013-04-18 00:00:00+00:00: Pearson Correlation: 0.894304567757
2013-04-19 00:00:00+00:00: Pearson Correlation: 0.204682970752
2013-04-22 00:00:00+00:00: Pearson Correlation: 0.203268615806
2013-04-23 00:00:00+00:00: Pearson Correlation: 0.408273152978
2013-04-24 00:00:00+00:00: Pearson Correlation: 0.696724629857
2013-04-25 00:00:00+00:00: Pearson Correlation: 0.829059086718
2013-04-26 00:00:00+00:00: Pearson Correlation: -0.0460241057536
2013-04-29 00:00:00+00:00: Pearson Correlation: 0.405794075795
2013-04-30 00:00:00+00:00: Pearson Correlation: 0.707738144101
2013-05-01 00:00:00+00:00: Pearson Correlation: 0.859529936421
2013-05-02 00:00:00+00:00: Pearson Correlation: 0.964752298038
2013-05-02 00:00:00+00:00: Selling 100 AAPL shares.
2013-05-02 00:00:00+00:00: Selling 100 GOOG shares.
2013-05-03 00:00:00+00:00: Pearson Correlation: 0.838557400323
2013-05-06 00:00:00+00:00: Pearson Correlation: 0.985339456603
2013-05-06 00:00:00+00:00: Selling 100 AAPL shares.
2013-05-06 00:00:00+00:00: Selling 100 GOOG shares.
2013-05-07 00:00:00+00:00: Pearson Correlation: 0.987890482366
[2013-06-04 16:48] INFO: Performance: Simulated 128 trading days out of 128.
[2013-06-04 16:48] INFO: Performance: first open: 2012-11-01 13:30:00+00:00
[2013-06-04 16:48] INFO: Performance: last close: 2013-05-07 20:00:00+00:00
2013-05-07 00:00:00+00:00: Buying 100 AAPL shares.
2013-05-07 00:00:00+00:00: Buying 100 GOOG shares.

Graphical analysis of its performance:


In [24]:
fig = plt.figure(figsize(18,12), dpi=1600)
ax1 = plt.subplot(411)
(data.SPX.pct_change() - data.SPX.pct_change()).plot()
(data.GOOG.pct_change() - data.SPX.pct_change()).plot(label='GOOG')
(data.AAPL.pct_change() - data.SPX.pct_change()).plot(label='AAPL')
plt.ylabel('Daily Return')
legend(loc='best')
plt.title("Adj Closing Prices adjusted for S&P movements")
plt.setp(ax2.get_xticklabels(), visible=False)

GOOG_AAPL_COR_V_SP500.buy_orders = np.asarray(GOOG_AAPL_COR_V_SP500.buy_orders)
GOOG_AAPL_COR_V_SP500.sell_orders = np.asarray(GOOG_AAPL_COR_V_SP500.sell_orders)
plt.title("GOOG_AAPL_COR_V_SP500 Results")

ax2 = plt.subplot(412, sharex=ax1)
plt.plot(GOOG_AAPL_COR_V_SP500.buy_orders[:,0], GOOG_AAPL_COR_V_SP500.buy_orders[:,1], color = 'r')
plt.plot(GOOG_AAPL_COR_V_SP500.sell_orders[:,0], GOOG_AAPL_COR_V_SP500.sell_orders[:,1], color = 'g')
plt.plot(GOOG_AAPL_COR_V_SP500.buy_orders[:,0], GOOG_AAPL_COR_V_SP500.buy_orders[:,1], '^', c='g', markersize=10, label='buy')
plt.plot(GOOG_AAPL_COR_V_SP500.sell_orders[:,0], GOOG_AAPL_COR_V_SP500.sell_orders[:,1], 'v', c='r', markersize=10, label='sell')
plt.ylabel('P-Value')
plt.grid(b=True)
plt.setp(ax1.get_xticklabels(), visible=False)
plt.legend()

ax3 = plt.subplot(413, sharex=ax1)
results_GOOG_AAPL_COR_V_SP500.portfolio_value.plot()
plt.setp(ax3.get_xticklabels(), visible=False)
plt.ylabel('Portfolio Value')
plt.legend(loc='best')

ax4 = plt.subplot(414, sharex=ax1)
results_GOOG_AAPL_COR_V_SP500.portfolio_value.pct_change().plot()
plt.ylabel('Portfolio % Change')
plt.legend()


Out[24]:
<matplotlib.legend.Legend at 0x12dd54e0>

In [25]:
results_GOOG_AAPL_COR_V_SP500.portfolio_value.describe()


Out[25]:
count        128.000000
mean     1049060.489758
std        34297.592741
min       996340.932000
25%      1012934.820750
50%      1065813.657000
75%      1078932.381000
max      1095169.828000
dtype: float64

In [26]:
results_GOOG_AAPL_COR_V_SP500.portfolio_value.pct_change().apply(lambda x: x * 100).describe()


Out[26]:
count    127.000000
mean       0.067915
std        0.466537
min       -1.068730
25%       -0.183413
50%        0.020627
75%        0.190214
max        3.172896
dtype: float64

In [27]:
# Plot the distribution of the returns
fig = plt.figure(figsize(8,4))
results_GOOG_AAPL_COR_V_SP500.portfolio_value.pct_change().dropna().plot(kind='kde')
plt.xlabel=('Returns')
title("The Distribution of the Returns for\nGOOG_AAPL_COR_V_SP500")


Out[27]:
<matplotlib.text.Text at 0x4ca45eb8>

The Results:

Our algorithm performed well. The portfolio ending value was approximately $1,088,569.669, thus our algorithm returned approximately 8.86% in just 128 days of trading. If we assume this performance for the rest of the year the algorithm would return 17.60%. Not too shabby. During our simulation the returns had a standard deviation of only 0.466%, meaning that it remained relatively low in its generation of alpha. Its greatest single day drawdown was only 1.068%, on its best day it returned 3.173%.

Can we do better? Let’s optimize the number of shares we order and use leverage:

Before we were only allowing our algorithm to trade 100 shares of either stock. Now, let’s let it trade as many shares as it’s able.

The secret sauce is this version is this line of code for Google and Apple respectively:

    self.trade_size_aapl = round(((self.capital_base * 0.75) / float(self.pricea)))
    self.trade_size_goog = round(((self.capital_base * 0.75) / float(self.priceg)))

This code allows the algorithm to fully utilize its assets under management by dividing the total sum of money allocated to the stock, (0.75% of our captial base) by the stock’s price to yield the maximum number of shares it can order. We constrain the allocation to 75% of assets under management with, self.capital_base * 0.75. Setting both stocks under this constraint allows it to be 150% long or short if two instances of Apple and Google are bought or sold, thus allowing the algorithm to trade on margin.

The algorithm is constrained to the standard 50% margin requirements by these additions to the decision logic:

    and self.orders < (2)   # for buy orders
    and self.orders > (-2)  # for sell orders

self.orders's value is tracked by adding a counter for every buy order and removing one for every sell order. This constrains the algorithm to a maximum of 2 orders in any direction and keeps it with in its margin allowance.

Until now our algorithms have been missing two key features of accurately simulating the performance of a trading strategy; slippage and commission. Because we are now trading with relatively large order sizes compared to our initial orders of 100 shares, (our new algorithm trades with fluctuating order sizes of over 1100 shares), we have to model the effect these larger orders may have on the market. At a very high level, price is a function of the quantity supplied and the quantity demanded. If large enough {buy, sell} orders are placed, they will cause a {shortage, surplus} in the market for that security thus {raising, lowering} its price. The effect of shifting the market price of a stock with large orders is called slippage, and so is a necessary component in simulating realistic performance. All of the previous algorithms assume that we can buy and sell the stocks for free, but sadly this isn’t the case for most of us. To model this transaction cost we will assume a fee of $9.99 per trade, as this is the current price for a standard retail account for many of the popular online brokers at the time of writing. This commission fee is effectively a tax on our returns and so its effect needs to be modeled if we want realistic results. The code to incorporate these features into our algorithm is shown below.

    # set slippage in our model, as a function of our trade size and the average trading
    # volume at the time of the trade
    self.set_slippage(slippage.VolumeShareSlippage(volume_limit=0.25, price_impact=0.1))

    #set commission $9.99 per trade. Cost per trade at TD Ameritrade at time of writing. 
    self.set_commission(commission.PerTrade(cost=9.99))

In [28]:
class GOOG_AAPL_COR_V_SP500_Optimized(TradingAlgorithm): # inherit from TradingAlgorithm
    """
    Google Apple Correlation algorithm adjusted for movements in the S&P500.

    An algorithm designed to exploit the correlation in the movement of Apple's and 
    Google's common stock. 
    """
    # need to add notional tollerances
    def initialize(self):
        self.capital_base = 1000000
        self.pricea = 0
        self.priceg = 0
        self.pricespx = 0
        self.trade_size_aapl = 0
        self.trade_size_goog = 0 
        self.window_length = 5 
        self.corr_tolerance = 0.9
        self.max_notional = self.capital_base + 0.1
        self.min_notional = self.capital_base * (-1) 
        self.pricealag = 0
        self.priceglag = 0
        self.pricespxlag = 0
        self.buy_orders = []
        self.sell_orders = [] 
        self.corr_values_aapl = []
        self.corr_values_goog = []
        self.orders = 0
        
        # set slippage in our model, as a function of our trade size and the average trading
        # volume at the time of the trade
        self.set_slippage(slippage.VolumeShareSlippage(volume_limit=0.25, price_impact=0.1))
        
        #set commission  $9.99 per trade. Cost per trade at TD Ameritrade at time of writing. 
        self.set_commission(commission.PerTrade(cost=9.99))
    
    def handle_data(self, data):
        self.pricea = data.AAPL.price 
        self.priceg = data.GOOG.price  
        self.pricespx = data.SPX.price
        
        # calculate trade size
        self.trade_size_aapl = round(((self.capital_base * 0.75) / float(self.pricea)))
        self.trade_size_goog = round(((self.capital_base * 0.75) / float(self.priceg)))

        # find percent change and substract movements from SPX
        aapl_mov, goog_mov = self.spx_adjust(
                                                data, self.pricea, self.priceg, self.pricespx, 
                                                self.pricealag, self.priceglag, self.pricespxlag
                                                )

        # calculate the correlation between the stocks
        corr, pval = self.correlation(data, self.pricea, self.priceg)
        print str(data.AAPL.datetime) + ': Pearson Correlation: ' + str(corr)

        #notional = self.portfolio.positions[data.AAPL].amount * pricea
        #notional = notional + self.portfolio.positions[data.GOOG].amount * priceg 

        # Decision Logic
        if goog_mov < 0 and np.abs(corr) > self.corr_tolerance and self.orders > (-2):
            self.order('AAPL',-(self.trade_size_aapl))
            self.sell_orders.append((data.AAPL.datetime, pval))
            self.orders -= 1
            print "{dt}: Selling {ts} AAPL shares.".format(dt = data.AAPL.datetime, ts = self.trade_size_aapl)
        elif goog_mov > 0 and np.abs(corr) > self.corr_tolerance and self.orders < (2):
            self.order('AAPL',(self.trade_size_aapl))
            self.buy_orders.append((data.AAPL.datetime, pval))
            self.orders += 1
            print "{dt}: Buying {ts} AAPL shares.".format(dt = data.AAPL.datetime, ts = self.trade_size_aapl)

        if aapl_mov < 0 and  np.abs(corr) > self.corr_tolerance and np.abs(self.orders) > (-2):
            self.order('GOOG',-(self.trade_size_goog))
            self.sell_orders.append((data.GOOG.datetime, pval))
            self.orders -= 1
            print "{dt}: Selling {ts} GOOG shares.".format(dt = data.GOOG.datetime, ts = self.trade_size_goog)
        elif aapl_mov > 0 and np.abs(corr) > self.corr_tolerance and np.abs(self.orders) < (2):
            self.order('GOOG', self.trade_size_goog)
            self.buy_orders.append((data.GOOG.datetime, pval))  
            self.orders += 1
            print "{dt}: Buying {ts} GOOG shares.".format(dt = data.GOOG.datetime, ts = self.trade_size_goog)

        # lag price variables 
        self.pricealag = data.AAPL.price
        self.priceglag = data.GOOG.price
        self.pricespxlag =  data.SPX.price

    def correlation(self, data, pricea, priceg):
        self.corr_values_aapl.append(pricea)
        self.corr_values_goog.append(priceg)
        corr = pearsonr(self.corr_values_aapl[-self.window_length:], self.corr_values_goog[-self.window_length:]) 
        return corr

    def per_change(self, data, begin, end):
        percent_change = ((end - begin)/begin)
        return percent_change
        
    def spx_adjust(self, data, pricea, priceg, pricespx, pricealag, priceglag, pricespxlag):
        spx_change = self.per_change(data, pricespx, self.pricespxlag)
        aapl_change = (self.per_change(data, pricea, self.pricealag) - spx_change)
        goog_change = (self.per_change(data, priceg, self.priceglag) - spx_change)
        return (aapl_change, goog_change)

In [29]:
GOOG_AAPL_COR_V_SP500_Optimized = GOOG_AAPL_COR_V_SP500_Optimized()
results_GOOG_AAPL_COR_V_SP500_Optimized = GOOG_AAPL_COR_V_SP500_Optimized.run(data)


2012-11-01 00:00:00+00:00: Pearson Correlation: nan
2012-11-02 00:00:00+00:00: Pearson Correlation: -1.0
2012-11-02 00:00:00+00:00: Selling 1314.0 AAPL shares.
2012-11-02 00:00:00+00:00: Buying 1090.0 GOOG shares.
2012-11-05 00:00:00+00:00: Pearson Correlation: 0.059824040231
2012-11-06 00:00:00+00:00: Pearson Correlation: 0.174659180436
2012-11-07 00:00:00+00:00: Pearson Correlation: 0.824233785309
2012-11-08 00:00:00+00:00: Pearson Correlation: 0.952297709192
2012-11-08 00:00:00+00:00: Buying 1403.0 AAPL shares.
2012-11-08 00:00:00+00:00: Buying 1150.0 GOOG shares.
2012-11-09 00:00:00+00:00: Pearson Correlation: 0.991554650251
2012-11-09 00:00:00+00:00: Selling 1379.0 AAPL shares.
2012-11-09 00:00:00+00:00: Selling 1131.0 GOOG shares.
2012-11-12 00:00:00+00:00: Pearson Correlation: 0.929368022202
2012-11-12 00:00:00+00:00: Selling 1390.0 AAPL shares.
2012-11-12 00:00:00+00:00: Buying 1126.0 GOOG shares.
2012-11-13 00:00:00+00:00: Pearson Correlation: 0.757576476824
2012-11-14 00:00:00+00:00: Pearson Correlation: 0.845836369332
2012-11-15 00:00:00+00:00: Pearson Correlation: 0.904363385855
2012-11-15 00:00:00+00:00: Buying 1435.0 AAPL shares.
2012-11-15 00:00:00+00:00: Buying 1159.0 GOOG shares.
2012-11-16 00:00:00+00:00: Pearson Correlation: 0.919167495476
2012-11-19 00:00:00+00:00: Pearson Correlation: 0.98644535697
2012-11-19 00:00:00+00:00: Selling 1333.0 AAPL shares.
2012-11-19 00:00:00+00:00: Selling 1122.0 GOOG shares.
2012-11-20 00:00:00+00:00: Pearson Correlation: 0.988017374005
2012-11-20 00:00:00+00:00: Selling 1345.0 AAPL shares.
2012-11-20 00:00:00+00:00: Buying 1119.0 GOOG shares.
2012-11-21 00:00:00+00:00: Pearson Correlation: 0.98614541901
2012-11-21 00:00:00+00:00: Buying 1343.0 AAPL shares.
2012-11-21 00:00:00+00:00: Buying 1126.0 GOOG shares.
2012-11-23 00:00:00+00:00: Pearson Correlation: 0.956502301266
2012-11-23 00:00:00+00:00: Selling 1123.0 GOOG shares.
2012-11-26 00:00:00+00:00: Pearson Correlation: -0.850795924042
2012-11-27 00:00:00+00:00: Pearson Correlation: -0.388234458157
2012-11-28 00:00:00+00:00: Pearson Correlation: 0.132856328942
2012-11-29 00:00:00+00:00: Pearson Correlation: 0.244364901771
2012-11-30 00:00:00+00:00: Pearson Correlation: -0.233575324747
2012-12-03 00:00:00+00:00: Pearson Correlation: 0.394085687777
2012-12-04 00:00:00+00:00: Pearson Correlation: 0.281478815016
2012-12-05 00:00:00+00:00: Pearson Correlation: 0.738307236796
2012-12-06 00:00:00+00:00: Pearson Correlation: 0.840028399437
2012-12-07 00:00:00+00:00: Pearson Correlation: 0.87515944915
2012-12-10 00:00:00+00:00: Pearson Correlation: 0.793381038641
2012-12-11 00:00:00+00:00: Pearson Correlation: 0.699662917774
2012-12-12 00:00:00+00:00: Pearson Correlation: 0.61994502866
2012-12-13 00:00:00+00:00: Pearson Correlation: 0.269620004501
2012-12-14 00:00:00+00:00: Pearson Correlation: -0.279590717582
2012-12-17 00:00:00+00:00: Pearson Correlation: -0.546140037064
2012-12-18 00:00:00+00:00: Pearson Correlation: -0.0881216339673
2012-12-19 00:00:00+00:00: Pearson Correlation: 0.403905418053
2012-12-20 00:00:00+00:00: Pearson Correlation: 0.755250505131
2012-12-21 00:00:00+00:00: Pearson Correlation: 0.339476408109
2012-12-24 00:00:00+00:00: Pearson Correlation: 0.549057229948
2012-12-26 00:00:00+00:00: Pearson Correlation: 0.739033938857
2012-12-27 00:00:00+00:00: Pearson Correlation: 0.744796824599
2012-12-28 00:00:00+00:00: Pearson Correlation: 0.821945371289
2012-12-31 00:00:00+00:00: Pearson Correlation: 0.466884246454
2013-01-02 00:00:00+00:00: Pearson Correlation: 0.876920310513
2013-01-03 00:00:00+00:00: Pearson Correlation: 0.927515534537
2013-01-03 00:00:00+00:00: Selling 1392.0 AAPL shares.
2013-01-03 00:00:00+00:00: Buying 1036.0 GOOG shares.
2013-01-04 00:00:00+00:00: Pearson Correlation: 0.494477226709
2013-01-07 00:00:00+00:00: Pearson Correlation: -0.387391976151
2013-01-08 00:00:00+00:00: Pearson Correlation: -0.927721502534
2013-01-08 00:00:00+00:00: Selling 1436.0 AAPL shares.
2013-01-08 00:00:00+00:00: Selling 1023.0 GOOG shares.
2013-01-09 00:00:00+00:00: Pearson Correlation: -0.909803583801
2013-01-09 00:00:00+00:00: Selling 1459.0 AAPL shares.
2013-01-10 00:00:00+00:00: Pearson Correlation: -0.233228339811
2013-01-11 00:00:00+00:00: Pearson Correlation: -0.446151532632
2013-01-14 00:00:00+00:00: Pearson Correlation: 0.806202475541
2013-01-15 00:00:00+00:00: Pearson Correlation: 0.907783047386
2013-01-16 00:00:00+00:00: Pearson Correlation: 0.696926220586
2013-01-17 00:00:00+00:00: Pearson Correlation: 0.442689440196
2013-01-18 00:00:00+00:00: Pearson Correlation: -0.496565907528
2013-01-22 00:00:00+00:00: Pearson Correlation: -0.717758128217
2013-01-23 00:00:00+00:00: Pearson Correlation: 0.91836915185
2013-01-23 00:00:00+00:00: Selling 1011.0 GOOG shares.
2013-01-24 00:00:00+00:00: Pearson Correlation: -0.601692961309
2013-01-25 00:00:00+00:00: Pearson Correlation: -0.703340810332
2013-01-28 00:00:00+00:00: Pearson Correlation: -0.708631151794
2013-01-29 00:00:00+00:00: Pearson Correlation: -0.942863822082
2013-01-29 00:00:00+00:00: Buying 1646.0 AAPL shares.
2013-01-29 00:00:00+00:00: Selling 995.0 GOOG shares.
2013-01-30 00:00:00+00:00: Pearson Correlation: 0.105071788809
2013-01-31 00:00:00+00:00: Pearson Correlation: 0.267677939369
2013-02-01 00:00:00+00:00: Pearson Correlation: -0.0734603761372
2013-02-04 00:00:00+00:00: Pearson Correlation: -0.199311330537
2013-02-05 00:00:00+00:00: Pearson Correlation: 0.0510478602377
2013-02-06 00:00:00+00:00: Pearson Correlation: 0.353566175356
2013-02-07 00:00:00+00:00: Pearson Correlation: 0.693378247595
2013-02-08 00:00:00+00:00: Pearson Correlation: 0.952514956078
2013-02-08 00:00:00+00:00: Selling 955.0 GOOG shares.
2013-02-11 00:00:00+00:00: Pearson Correlation: 0.922284099348
2013-02-11 00:00:00+00:00: Buying 1563.0 AAPL shares.
2013-02-11 00:00:00+00:00: Selling 959.0 GOOG shares.
2013-02-12 00:00:00+00:00: Pearson Correlation: 0.855718558992
2013-02-13 00:00:00+00:00: Pearson Correlation: 0.442512222602
2013-02-14 00:00:00+00:00: Pearson Correlation: -0.15909805662
2013-02-15 00:00:00+00:00: Pearson Correlation: -0.660823444996
2013-02-19 00:00:00+00:00: Pearson Correlation: -0.873349113446
2013-02-20 00:00:00+00:00: Pearson Correlation: -0.373572157847
2013-02-21 00:00:00+00:00: Pearson Correlation: -0.101445899412
2013-02-22 00:00:00+00:00: Pearson Correlation: 0.398375188553
2013-02-25 00:00:00+00:00: Pearson Correlation: 0.935757136186
2013-02-25 00:00:00+00:00: Selling 948.0 GOOG shares.
2013-02-26 00:00:00+00:00: Pearson Correlation: 0.488289511759
2013-02-27 00:00:00+00:00: Pearson Correlation: 0.236926672758
2013-02-28 00:00:00+00:00: Pearson Correlation: -0.134727207432
2013-03-01 00:00:00+00:00: Pearson Correlation: -0.800766068617
2013-03-04 00:00:00+00:00: Pearson Correlation: -0.966418239347
2013-03-05 00:00:00+00:00: Pearson Correlation: -0.612146269391
2013-03-06 00:00:00+00:00: Pearson Correlation: -0.523858670059
2013-03-07 00:00:00+00:00: Pearson Correlation: 0.128313159843
2013-03-08 00:00:00+00:00: Pearson Correlation: 0.856768169064
2013-03-11 00:00:00+00:00: Pearson Correlation: 0.37064308425
2013-03-12 00:00:00+00:00: Pearson Correlation: 0.694439233109
2013-03-13 00:00:00+00:00: Pearson Correlation: 0.848864875018
2013-03-14 00:00:00+00:00: Pearson Correlation: 0.583850851016
2013-03-15 00:00:00+00:00: Pearson Correlation: -0.382247521161
2013-03-18 00:00:00+00:00: Pearson Correlation: -0.986326278298
2013-03-18 00:00:00+00:00: Buying 1646.0 AAPL shares.
2013-03-18 00:00:00+00:00: Selling 928.0 GOOG shares.
2013-03-19 00:00:00+00:00: Pearson Correlation: -0.982469497378
2013-03-20 00:00:00+00:00: Pearson Correlation: -0.916359799195
2013-03-20 00:00:00+00:00: Buying 1659.0 AAPL shares.
2013-03-21 00:00:00+00:00: Pearson Correlation: -0.69849547277
2013-03-22 00:00:00+00:00: Pearson Correlation: -0.483088392126
2013-03-25 00:00:00+00:00: Pearson Correlation: -0.769950032764
2013-03-26 00:00:00+00:00: Pearson Correlation: -0.692494102481
2013-03-27 00:00:00+00:00: Pearson Correlation: 0.534907310429
2013-03-28 00:00:00+00:00: Pearson Correlation: 0.973183362731
2013-03-28 00:00:00+00:00: Buying 1694.0 AAPL shares.
2013-04-01 00:00:00+00:00: Pearson Correlation: 0.726670249705
2013-04-02 00:00:00+00:00: Pearson Correlation: 0.143611794748
2013-04-03 00:00:00+00:00: Pearson Correlation: -0.465442720063
2013-04-04 00:00:00+00:00: Pearson Correlation: -0.395440571443
2013-04-05 00:00:00+00:00: Pearson Correlation: 0.888941897899
2013-04-08 00:00:00+00:00: Pearson Correlation: 0.799236827344
2013-04-09 00:00:00+00:00: Pearson Correlation: 0.759685868182
2013-04-10 00:00:00+00:00: Pearson Correlation: 0.457328874099
2013-04-11 00:00:00+00:00: Pearson Correlation: 0.780718813282
2013-04-12 00:00:00+00:00: Pearson Correlation: 0.863304390263
2013-04-15 00:00:00+00:00: Pearson Correlation: 0.724997330538
2013-04-16 00:00:00+00:00: Pearson Correlation: 0.623692113603
2013-04-17 00:00:00+00:00: Pearson Correlation: 0.744004178512
2013-04-18 00:00:00+00:00: Pearson Correlation: 0.894304567757
2013-04-19 00:00:00+00:00: Pearson Correlation: 0.204682970752
2013-04-22 00:00:00+00:00: Pearson Correlation: 0.203268615806
2013-04-23 00:00:00+00:00: Pearson Correlation: 0.408273152978
2013-04-24 00:00:00+00:00: Pearson Correlation: 0.696724629857
2013-04-25 00:00:00+00:00: Pearson Correlation: 0.829059086718
2013-04-26 00:00:00+00:00: Pearson Correlation: -0.0460241057536
2013-04-29 00:00:00+00:00: Pearson Correlation: 0.405794075795
2013-04-30 00:00:00+00:00: Pearson Correlation: 0.707738144101
2013-05-01 00:00:00+00:00: Pearson Correlation: 0.859529936421
2013-05-02 00:00:00+00:00: Pearson Correlation: 0.964752298038
2013-05-02 00:00:00+00:00: Selling 904.0 GOOG shares.
2013-05-03 00:00:00+00:00: Pearson Correlation: 0.838557400323
2013-05-06 00:00:00+00:00: Pearson Correlation: 0.985339456603
2013-05-06 00:00:00+00:00: Selling 871.0 GOOG shares.
2013-05-07 00:00:00+00:00: Pearson Correlation: 0.987890482366
[2013-06-04 16:48] INFO: Performance: Simulated 128 trading days out of 128.
[2013-06-04 16:48] INFO: Performance: first open: 2012-11-01 13:30:00+00:00
[2013-06-04 16:48] INFO: Performance: last close: 2013-05-07 20:00:00+00:00
2013-05-07 00:00:00+00:00: Buying 1635.0 AAPL shares.

In [30]:
fig = plt.figure(figsize(18,12), dpi=1600)
plt.title("GOOG_AAPL_COR_V_SP500_Optimized Results")

# plot 1 
ax1 = plt.subplot(411)
(data.SPX.pct_change() - data.SPX.pct_change()).plot()
(data.GOOG.pct_change() - data.SPX.pct_change()).plot(label='GOOG')
(data.AAPL.pct_change() - data.SPX.pct_change()).plot(label='AAPL')
plt.ylabel("Daily Return")
legend(loc='best')
plt.setp(ax2.get_xticklabels(), visible=False)

# prepare data for plot 2
GOOG_AAPL_COR_V_SP500_Optimized.buy_orders = np.asarray(GOOG_AAPL_COR_V_SP500_Optimized.buy_orders)
GOOG_AAPL_COR_V_SP500_Optimized.sell_orders = np.asarray(GOOG_AAPL_COR_V_SP500_Optimized.sell_orders)

# plot 2
ax2 = plt.subplot(412, sharex=ax1)
plt.plot(GOOG_AAPL_COR_V_SP500_Optimized.buy_orders[:,0], GOOG_AAPL_COR_V_SP500_Optimized.buy_orders[:,1], color = 'g')
plt.plot(GOOG_AAPL_COR_V_SP500_Optimized.sell_orders[:,0], GOOG_AAPL_COR_V_SP500_Optimized.sell_orders[:,1], color = 'r')
plt.plot(GOOG_AAPL_COR_V_SP500_Optimized.buy_orders[:,0], GOOG_AAPL_COR_V_SP500_Optimized.buy_orders[:,1], '^', c='g', markersize=10, label='buy')
plt.plot(GOOG_AAPL_COR_V_SP500_Optimized.sell_orders[:,0], GOOG_AAPL_COR_V_SP500_Optimized.sell_orders[:,1], 'v', c='r', markersize=10, label='sell')
plt.ylabel('P-Value')
plt.grid(b=True)
plt.setp(ax1.get_xticklabels(), visible=False)
plt.legend()

# plot 3
ax3 = plt.subplot(413, sharex=ax1)
results_GOOG_AAPL_COR_V_SP500_Optimized.portfolio_value.plot()
plt.setp(ax3.get_xticklabels(), visible=False)
plt.ylabel('Portfolio Value')
plt.legend(loc='best')

# plot 4
ax4 = plt.subplot(414, sharex=ax1)
results_GOOG_AAPL_COR_V_SP500_Optimized.portfolio_value.pct_change().plot()
plt.ylabel('Portfolio % Change')
plt.legend()


Out[30]:
<matplotlib.legend.Legend at 0x2f036940>

In [31]:
results_GOOG_AAPL_COR_V_SP500_Optimized.portfolio_value.describe()


Out[31]:
count        128.000000
mean     1092447.654194
std        61774.921741
min       973494.685625
25%      1041830.935625
50%      1129349.983065
75%      1147683.571250
max      1173102.198750
dtype: float64

In [32]:
results_GOOG_AAPL_COR_V_SP500_Optimized.portfolio_value.pct_change().apply(lambda x: x * 100).describe()


Out[32]:
count    127.000000
mean       0.109009
std        1.040242
min       -2.956030
25%       -0.293096
50%        0.012775
75%        0.464028
max        8.133918
dtype: float64

In [33]:
# Plot the distribution of the returns
fig = plt.figure(figsize(8,4))
results_GOOG_AAPL_COR_V_SP500_Optimized.portfolio_value.pct_change().dropna().plot(kind='kde')
plt.xlabel=('Returns')
title("The Distribution of the Returns for\nGOOG_AAPL_COR_V_SP500_Optimized")


Out[33]:
<matplotlib.text.Text at 0x4aaf27b8>

The Results:

Our algorithm performed well. It finished the 128 days of trading with a portfolio value of $1,140,775.184 million dollars, a return of 14.10%. On its single greatest day it retuned 8.133% and on its worst; it had a drawdown of 2.95%. On average it returned 0.109% a day, just about a 10th of a percent. The standard deviation of our returns was a mere 1.04%; meaning that despite the additional leverage, and so increased volatility, it remained a relatively low volatility generator of alpha. If this performance is assumed throughout the rest of the year, the algorithm would return would be 28.20%. This would greatly outpace the market and would have a superior risk profile, with regards to volatility, for the average investor

Aggregated performance between models:


In [34]:
fig = plt.figure(figsize(18,8), dpi=1600)
ax1 = plt.subplot(211)
results_GOOG_AAPL_COR.portfolio_value.plot(label='GOOG_AAPL_COR')
results_GOOG_AAPL_COR_V_SP500.portfolio_value.plot(label='GOOG_AAPL_COR_V_SP500')
results_GOOG_AAPL_COR_V_SP500_Optimized.portfolio_value.plot(label='GOOG_AAPL_COR_V_SP500_Optimized')
plt.setp(ax3.get_xticklabels(), visible=False)
plt.ylabel('Portfolio Value')
plt.legend(loc='best')
plt.title('Aggreated Performance')

ax1 = plt.subplot(212, sharex=ax1)
results_GOOG_AAPL_COR.portfolio_value.pct_change().plot(label='GOOG_AAPL_COR')
results_GOOG_AAPL_COR_V_SP500.portfolio_value.pct_change().plot(label='GOOG_AAPL_COR_V_SP500')
results_GOOG_AAPL_COR_V_SP500_Optimized.portfolio_value.pct_change().plot(label='GOOG_AAPL_COR_V_SP500_Optimized')
plt.ylabel('Portfolio % Change')
plt.legend(loc='best')


Out[34]:
<matplotlib.legend.Legend at 0x47b805f8>

Version Control


In [37]:
!git add "GOOG V. AAPL Correlation Arb".ipynb

In [38]:
!git commit


[master 9dfb70a] added KDEs to results analysis
 1 file changed, 181 insertions(+), 142 deletions(-)

In [36]: